<?php

use Carbon\Carbon;
class TorneosController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/
	
	public function index()
	{
		
		$torneos= array(
			
			'torneos' => Torneo::orderBy('created_at','descending')->paginate(4)
		);
		
		return View::make('contents.torneos',$torneos)->with('title','Torneos :: Paintballed');
	}
	
	public function torneo($id){
		
		$torneo = Torneo::find($id);
		
		$data=array('torneo'=>$torneo);
		
		$inscribirse=Input::get('inscribirse');
		$desinscribirse=Input::get('desinscribirse');
		
		$validator = Validator::make(Input::all(), array(
				'comentario'=>'required'
		));
		
		if($validator->passes()){
			$comentario= new Comentario();
			$comentario->contenido=Input::get('comentario');
				
			Auth::user()->comentarios()->save($comentario);
				
			$torneo->comentarios()->attach($comentario);
		}
		
		if(empty($inscribirse) && empty($desinscribirse)){
		
			if(!empty($torneo->password)){
				if(Hash::check(Input::get('password'), $torneo->password)){
					return View::make('contents.torneo',$data)->with('title','Torneo '.$id.' :: Paintballed');
				} else {
					return Redirect::route('torneos');
				}
			} else {
				return View::make('contents.torneo',$data)->with('title','Torneo '.$id.' :: Paintballed');
			}
		} else {
			if(empty($inscribirse)){
				$torneo->users()->detach(Auth::user()->id);
			} else if($torneo->users()->count()<$torneo->plazas){
				$torneo->users()->attach(Auth::user()->id);
			}
			return View::make('contents.torneo',$data)->with('title','Torneo '.$id.' :: Paintballed');
		}
	}

}